/**
 * 
 */
package com.kelaite.procurement.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.dto.LocaleDTO;
import com.kelaite.procurement.entity.TLocale;
import com.kelaite.procurement.exception.NullObjectException;
import com.kelaite.procurement.repository.LocaleRepository;
import com.kelaite.procurement.service.LocaleService;
import com.kelaite.procurement.utils.ConvertUtil;

@Service
@Transactional
public class LocaleServiceImpl implements LocaleService {

	@Autowired
	private LocaleRepository localeRepository;

	@PersistenceContext
	private EntityManager em;

	@Override
	public LocaleDTO save(LocaleDTO localeDTO) {

		if (null == localeDTO) {
			throw new NullObjectException("LocaleDTO is null. ");
		}
		TLocale dbLocale = ConvertUtil.convertObj(localeDTO, TLocale.class);
		return ConvertUtil.convertObj(localeRepository.save(dbLocale),
				LocaleDTO.class);
	}

	@Override
	public void deleteByPrimaryKey(Long id) {

		localeRepository.delete(id);
	}

	@Override
	public void deleteByObject(LocaleDTO persistence) {

		localeRepository.delete(ConvertUtil.convertObj(persistence,
				TLocale.class));
	}

	@Override
	public LocaleDTO getObject(Long id) {

		return ConvertUtil.convertObj(localeRepository.findOne(id),
				LocaleDTO.class);
	}

	@Override
	public List<LocaleDTO> getAll() {

		return ConvertUtil.convertList(localeRepository.findAll(),
				LocaleDTO.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LocaleDTO> getByProperty(String property, Object value) {

		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TLocale.class).add(
				Restrictions.eq(property, value));
		return criteria.list();
	}

}
